package com.mairuide._frame.utils.excellistener;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.websocket.server.ServerEndpoint;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.mairuide._frame.utils.ReflectUtils;
import com.mairuide._frame.utils.SecurityUtil;
import com.mairuide._frame.utils.SpringUtil;
import com.mairuide.bill.DealFlow;
import com.mairuide.bill.DealFlowService;
import com.mairuide.bill.titlepool.DealFlowTitle;
import com.mairuide.bill.titlepool.DealFlowTitlePool;
import com.mairuide.bill.titlepool.DealFlowTitlePoolRepository;
import com.mairuide.bill.titlepool.DealFlowTitleRepository;
import com.mairuide.bill.utils.DateUtils;
import com.mairuide.bill.utils.ExcelUtils;
import com.mairuide.exceltitle_dict.enum2.FieldTypeEnum;
import com.mairuide.exceltitle_dict.enum2.PackageNameEnum;
import com.mairuide.exceltitle_dict.pojo.ExceltitleDict;
import com.mairuide.exceltitle_dict.service.ExceltitleDictService;

/**
 * Created by songRT
 * on 2019/1/8 11:08.
 * 匹配通用标题池的大excel文件
 */
@Service
public class DefaultDealFlowExcelListener extends AnalysisEventListener {
    private  List<DealFlow> list = new ArrayList<DealFlow>();
    private  List<DealFlow> data = new ArrayList<DealFlow>();
    private String columns[] = new String[256];
    private Map<String , String> titleMap = new HashMap<String , String>();
    private Map<String,Object> paraMap = new HashMap<String,Object>();  //参数MAP
    private Map<String,Object> resultMap = new HashMap<String,Object>();  //结果MAP
    @Override
    public void invoke(Object object, AnalysisContext context) {
    	//第一步获取标题行和sheet名
    	if(context.getCurrentRowNum()!=null && context.getCurrentRowNum()==0) {
    		if(object!=null) {
    			List<String> s = (List<String>) object;
                //判断这一行是否有合并单元格，或者列数小于5
                if (s.size()<5) return;
                if (s.get(3)==null || "".equals(s.get(3).toString().trim())) return;
                //标题行与标题池做对应，找到标题对应字段
                for (int j=0;j<s.size();j++){
                    String cellData = s.get(j)==null?"":s.get(j).toString();
                    String replace = cellData.replace(" ", "");
//                    try {
//    					replace = SecurityUtil.encrypt(replace);
//    				} catch (UnsupportedEncodingException e) {
//    					e.printStackTrace();
//    				}
                    DealFlowTitlePoolRepository dealFlowTitlePoolRepository = SpringUtil.getBean(DealFlowTitlePoolRepository.class);
                    DealFlowTitleRepository dealFlowTitleRepository = SpringUtil.getBean(DealFlowTitleRepository.class);
                    DealFlowTitlePool dealPool = dealFlowTitlePoolRepository.findByBankTitleName(replace);
                    if (null!=dealPool&&dealPool.getIsDelete()==0){
                        DealFlowTitle one = dealFlowTitleRepository.findOne(dealPool.getTitleId());
                        titleMap.put(cellData ,one.getMappingField());
                        columns[j] = cellData;
                    }
                }
    		}
            //标题对应完毕，跳出循环
    		return;
    	}
        List<String> s = (List<String>)object;
        DealFlow deal = new DealFlow();
        //此行第一格内出现：就说明这一行不是数据行，跳过
        if(s.get(0)!=null && s.get(0).toString().indexOf("：")>0) return;
        //交易日期两个字段就拼接，一个字段则不拼接
        String date = "";
        for (int j=0;j<s.size();j++){
        	Object content = s.get(j);
        	if (columns[j]!=null && content!=null){
                String cellData = content.toString();
                //对于出现了不固定的多行标题做判断，如果此行为标题行，直接跳过外层循环
                if (columns[j]!=null && columns[j].equals(cellData)) return;
                cellData = cellData.trim();
                //把对应标题的数据放入实体中
                switch (titleMap.get(columns[j])){
                    case "交易主体": deal.setAccountBody(cellData);break;
                    case "交易主体账号": deal.setAccountBodyNumber(cellData);break;
                    case "交易主体卡号": deal.setAccountBodyCard(cellData);break;
                    case "收付标志":
                        if ("0".equals(cellData)||"C".equals(cellData)||"进".equals(cellData)||"贷".equals(cellData)){
                            deal.setSign(0);
                        } else if ("1".equals(cellData)||"D".equals(cellData)||"出".equals(cellData)||"借".equals(cellData)){
                            deal.setSign(1);
                        }break;
                    case "日期时间":
                        if (cellData.length()<6)cellData = "000000";
                        date += " "+cellData;
                        date = date.trim() ;break ;
                        //deal.setTradeDate(date.trim());break;
                    case "交易对手": deal.setAccountRival(cellData);break;
                    case "交易对手账号": deal.setAccountRivalNumber(cellData);break;
                    case "交易对手卡号": deal.setAccountRivalCard(cellData);break;
                    case "交易金额":
                        if (!"".equals(cellData)&&cellData!=null&&new BigDecimal(cellData).compareTo(new BigDecimal(0))!=0){
                            deal.setAccountMoney(new BigDecimal(cellData));
                            if (columns[j].equals("贷方发生额")&&new BigDecimal(cellData).compareTo(new BigDecimal(0))>0){
                                deal.setSign(0);
                            } else if (columns[j].equals("借方发生额")&&new BigDecimal(cellData).compareTo(new BigDecimal(0))>0){
                                deal.setSign(1);
                            }
                        }break;
                    case "交易后余额": if (!"".equals(cellData)&&cellData!=null)deal.setSurplusMoney(new BigDecimal( cellData));break;
                    case "摘要": deal.setContentAbstract( cellData);break;
                    case "交易主体归属行": deal.setAccountBodyBank( cellData);break;
                    case "交易对手归属行": deal.setAccountRivalBank( cellData);break;
                    case "交易地点": deal.setAccountAddress( cellData);break;
                    case "交易方式": deal.setAccountMode( cellData);break;
                    case "交易流水号": deal.setSerialNumber(cellData);break;
                    case "MAC地址": deal.setMacAddress( cellData);break;
                    case "IP地址": deal.setIpAddress( cellData);break;
                    case "币种": deal.setCurrency( cellData);break;
                    case "备注": deal.setRemarks( cellData);break;
                    case "柜员号": deal.setTellerNumber( cellData);break;
                    case "交易机构号": deal.setTradingOrganizationNumber( cellData);break;
                    case "对方机构号": deal.setInstitutionNumber( cellData);break;
                    default: break;
                }
            }
        	
        	Date date1 = DateUtils.getDate(date);
            if (date1!=null)deal.setTradeDate(new Timestamp(date1.getTime()));
            if (deal.getAccountBodyCard()==null||"".equals(deal.getAccountBodyCard())){
                deal.setAccountBodyCard(deal.getAccountBodyNumber());
            }
            if (deal.getAccountRivalCard()==null||"".equals(deal.getAccountRivalCard())){
                deal.setAccountRivalCard(deal.getAccountRivalNumber());
            }
        }
        	
        data.add(deal);
        if(data.size()>=10000){
            //list.addAll(data);
            doSomething();
            Integer size=0;
            if (resultMap.containsKey("successNum")){
                size = (Integer) resultMap.get("successNum");
                size+=data.size();
            }else{
                size=data.size();
            }
            resultMap.put("successNum",size);
            data = new ArrayList<DealFlow>();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        //list.addAll(data);
        Integer size=0;
        if (resultMap.containsKey("successNum")){
            size = (Integer) resultMap.get("successNum");
            size+=data.size();
        }else{
            size=data.size();
        }
        resultMap.put("successNum",size);
        doSomething();
        data = new ArrayList<DealFlow>();
    }
    public void doSomething(){
        for (int i = 0; i < data.size(); i++) {
            DealFlow dealFlow = data.get(i);
            dealFlow.setUuid((String)paraMap.get("uuid"));
            dealFlow.setCasemanageId((String)paraMap.get("uid"));
            dealFlow.setCreateId((Integer) paraMap.get("platManagerId"));
            dealFlow.setCreateTime(new Timestamp(System.currentTimeMillis()));
            dealFlow.setIsDelete(0);
        }
        DealFlowService dealFlowService = SpringUtil.getBean(DealFlowService.class);
        dealFlowService.batchSave(data);
    }

    public List<DealFlow> getList() {
        return list;
    }

    public void setList(List<DealFlow> list) {
        this.list = list;
    }

    public Map<String, Object> getParaMap() {
        return paraMap;
    }

    public void setParaMap(Map<String, Object> paraMap) {
        this.paraMap = paraMap;
    }

    public Map<String, Object> getResultMap() {
        return resultMap;
    }

    public void setResultMap(Map<String, Object> resultMap) {
        this.resultMap = resultMap;
    }

	public List<DealFlow> getData() {
		return data;
	}

	public void setData(List<DealFlow> data) {
		this.data = data;
	}

	public String[] getColumns() {
		return columns;
	}

	public void setColumns(String[] columns) {
		this.columns = columns;
	}

	public Map<String, String> getTitleMap() {
		return titleMap;
	}

	public void setTitleMap(Map<String, String> titleMap) {
		this.titleMap = titleMap;
	}
}
